package com.momoc.multi.chat.room.core.producer;

import com.momoc.multi.chat.room.common.dto.AuroraQueueMessageDTO;
import com.momoc.multi.chat.room.common.dto.UserOnlineCacheDTO;
import com.momoc.multi.chat.room.core.consumer.RabbitMessageConfig;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author momoc
 * @version 1.0
 * @className ProducerDispatchMessageCenter
 * @description
 * @date 2024/5/28 12:02
 */

@RequiredArgsConstructor
@Component
public class ProducerDispatchMessageCenter {

    final RabbitTemplate  rabbitTemplate;
    final RabbitMessageConfig rabbitMessageConfig;

    /**
     * 将消息发送到消息队列中
     * @param message
     */
    public void sendMessageToQueue(AuroraQueueMessageDTO message) {
        Map<String, List<UserOnlineCacheDTO>> machineIdUserMap = message.getUserList().stream().collect(Collectors.groupingBy(UserOnlineCacheDTO::getMachineId));
        for (Map.Entry<String, List<UserOnlineCacheDTO>> listEntry : machineIdUserMap.entrySet()) {
            String machineId = listEntry.getKey();
            //交换机
            String exchangeName = String.format(RabbitMessageConfig.INSTANCE_EXCHANGE_NAME_PREFIX, machineId);
            AuroraQueueMessageDTO auroraQueueMessageDTO = new AuroraQueueMessageDTO();
            auroraQueueMessageDTO.setMessageNum(message.getMessageNum());
            auroraQueueMessageDTO.setMessageBody(message.getMessageBody());
            auroraQueueMessageDTO.setUserList(listEntry.getValue());
            rabbitTemplate.convertAndSend(exchangeName, "", auroraQueueMessageDTO);
        }
    }

}
